package com.appkubes.fintech.restful.application.user.service.impl;

import com.appkubes.fintech.core.po.FintechUser;
import com.appkubes.fintech.core.po.FintechUserBankCard;
import com.appkubes.fintech.restful.application.user.dao.UserBankCardDao;
import com.appkubes.fintech.restful.application.user.dao.UserDao;
import com.appkubes.fintech.restful.application.user.domain.UserCertificateDomain;
import com.appkubes.fintech.restful.application.user.entity.vo.UserBankCardVO;
import com.appkubes.fintech.restful.application.user.service.UserBankCardService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

@Service
@Data
@Slf4j
public class UserBankCardServiceImpl implements UserBankCardService {
    @Resource
    UserBankCardDao userBankCardDao;

    @Resource
    UserCertificateDomain certificateService;

    @Resource
    UserDao userDao;

    @Override
    public FintechUserBankCard getBankCard(String userKey) {
        FintechUser user = userDao.selectByPrimaryKey(userKey);
        if(Objects.isNull(user)){
            return null;
        }
        if(!Integer.valueOf(1).equals(user.getIsBankCardCertificate())){
            return null;
        }
        return userBankCardDao.selectByPrimaryKey(userKey);
    }

    @Override
    public Integer addBankCard(UserBankCardVO bankCardVO) {
        String userKey = bankCardVO.getUserKey();
        Integer effectRow = 0;
        FintechUserBankCard userBankCard = userBankCardDao.selectByPrimaryKey(userKey);
        if (userBankCard == null) {
            //补偿机制
            userBankCard = new FintechUserBankCard();
            BeanUtils.copyProperties(bankCardVO, userBankCard);
            effectRow += userBankCardDao.insertSelective(userBankCard);
        }
        BeanUtils.copyProperties(bankCardVO, userBankCard);
        effectRow += userBankCardDao.updateByPrimaryKey(userBankCard);
        log.info("begin updateBankCardCertificate,userKey is {}",userKey);
        System.out.println("begin updateBankCardCertificate,userKey is " + userKey);
        int row1 = certificateService.updateBankCardCertificate(userKey, 1);
        log.info("end updateBankCardCertificate,userKey is {},row is {}",userKey,row1);
        System.out.println("end updateBankCardCertificate,userKey is "  + userKey + ", row is "+ row1);
        return effectRow;
    }
}
